<template>
  <t-form
    ref="form"
    class="item-container"
    :class="[`register-${type}`]"
    :data="formData"
    :rules="FORM_RULES"
    label-width="0"
    @submit="onSubmit"
  >
    <template v-if="type === 'account'">
      <t-form-item name="account">
        <!-- 用 t-popup 包裹账号输入框，实现气泡提示 -->
        <t-popup
          :visible="showAccountRule"
          placement="top-left"
          :attach="attachTarget"
          :overlay-style="{ padding: '0', zIndex: 2000 }"
        >
          <!-- 气泡内容：账号规则 -->
          <template #content>
            <div style="padding: 12px 16px; width: 320px">
              <div style="color: #52c41a">✔ 账号只能由数字和字母组成</div>
            </div>
          </template>
          <t-input
            v-model="formData.account"
            size="large"
            placeholder="请输入您的账号"
            @focus="showAccountRule = true"
            @blur="showAccountRule = false"
          >
            <template #prefix-icon>
              <t-icon name="user" />
            </template>
          </t-input>
        </t-popup>
      </t-form-item>
    </template>

    <t-form-item name="password">
      <!-- 用 t-popup 包裹密码输入框，实现气泡提示 -->
      <t-popup
        :visible="showPasswordRule"
        placement="top-left"
        :attach="attachTarget"
        :overlay-style="{ padding: '0', zIndex: 2000 }"
      >
        <!-- 气泡内容：密码规则 -->
        <template #content>
          <div style="padding: 12px 16px; width: 320px">
            <div style="color: #52c41a">✔ 6-20个字符，只能由字母或数字组成</div>
          </div>
        </template>
        <t-input
          v-model="formData.password"
          size="large"
          :type="showPsw ? 'text' : 'password'"
          clearable
          placeholder="请输入登录密码"
          @focus="showPasswordRule = true"
          @blur="showPasswordRule = false"
        >
          <template #prefix-icon>
            <t-icon name="lock-on" />
          </template>
          <template #suffix-icon>
            <t-icon :name="showPsw ? 'browse' : 'browse-off'" @click="showPsw = !showPsw" />
          </template>
        </t-input>
      </t-popup>
    </t-form-item>

    <t-form-item name="confirmPassword">
      <t-input
        v-model="formData.confirmPassword"
        size="large"
        :type="showConfirmPsw ? 'text' : 'password'"
        clearable
        placeholder="请再次输入登录密码"
      >
        <template #prefix-icon>
          <t-icon name="lock-on" />
        </template>
        <template #suffix-icon>
          <t-icon :name="showConfirmPsw ? 'browse' : 'browse-off'" @click="showConfirmPsw = !showConfirmPsw" />
        </template>
      </t-input>
    </t-form-item>

    <t-form-item class="check-container" name="checked">
      <t-checkbox v-model="formData.checked">我已阅读并同意 </t-checkbox> <span>用户服务协议</span> 和
      <span>隐私声明</span>
    </t-form-item>

    <t-form-item>
      <t-button block size="large" type="submit"> 注册 </t-button>
    </t-form-item>
  </t-form>
</template>
<script setup lang="ts">
import { register } from '@/api/userController';
import type { FormRule, SubmitContext } from 'tdesign-vue-next';
import { MessagePlugin } from 'tdesign-vue-next';
import { ref } from 'vue';

const emit = defineEmits(['register-success']);

const INITIAL_DATA = {
  // phone: '',
  account: '',
  password: '',
  confirmPassword: '',
  checked: false,
};

const FORM_RULES: Record<string, FormRule[]> = {
  account: [{ required: true, message: '账号必填', type: 'error' }],
  password: [{ required: true, message: '密码必填', type: 'error' }],
  confirmPassword: [{ required: true, message: '确认密码必填', type: 'error' }],
};

const attachTarget = () => {
  return document.body;
};

const type = ref('account');

const form = ref();
const formData = ref({ ...INITIAL_DATA });

const showPsw = ref(false);
const showConfirmPsw = ref(false);
const showPasswordRule = ref(false);
const showAccountRule = ref(false);

const validateForm = () => {
  // 中文注释：校验账号格式
  if (formData.value.account && !/^[a-zA-Z0-9]+$/.test(formData.value.account)) {
    console.log('账号只能由数字和字母组成');
    MessagePlugin.error('账号只能由数字和字母组成');
    return false;
  }

  // 校验密码长度
  if (formData.value.password.length < 6 || formData.value.password.length > 20) {
    MessagePlugin.error('密码长度必须在6到20位');
    return false;
  }
  // 校验两次密码一致
  if (formData.value.password !== formData.value.confirmPassword) {
    MessagePlugin.error('两次输入的密码不一致');
    return false;
  }
  return true;
};

const onSubmit = async (ctx: SubmitContext) => {
  // 中文注释：注册时提交账号、密码和确认密码
  if (ctx.validateResult === true) {
    if (!formData.value.checked) {
      MessagePlugin.error('请同意用户服务协议和用户隐私声明');
      return;
    }
    if (!validateForm()) {
      return;
    }
    try {
      const res = await register(formData.value);
      if (res.data.code === 200) {
        MessagePlugin.success('注册成功');
        emit('register-success');
      } else {
        MessagePlugin.error(res.message);
      }
    } catch (e) {
      MessagePlugin.error(e.message);
    }
  }
};

const switchType = (val: string) => {
  form.value.reset();
  type.value = val;
};
</script>
<style lang="less" scoped>
@import '../index.less';
</style>
